import { FormModal } from "@/components/modal/form.modal"
import { Field_Search } from "@/components/utils/field.list"
import hetongService from "@/services/hetong.service"
import { StoreContext } from "@/store"
import { AsyncModal, OperateRender, IndexRender, FormRender, ListTable, DateRender } from "@whzhuke/antd"
import { useMobx } from "@whzhuke/mobx"
import { Button, Col, Modal, Row, Space } from "antd"
import { useForm } from "antd/es/form/Form"
import React, { useCallback, useContext } from "react"
import { ConfirmHetong } from "@/components/form/hetongguanli/Confirm.hetong"
import { functionCommon } from "@whzhuke/common"

// 交付期单位映射：数字 -> 文字（用于表格显示）
const deliveryUnitDisplayMap: Record<number, string> = {
  1: "天",
  2: "月"
}

// 合同测试数据
// const hetongTestData = [
//   {
//     id: 1,
//     code: "HT202401001",
//     name: "铝材采购合同",
//     fileUrl: "/files/202511211700183983571.pdf",
//     delivery: 30,
//     deliveryUnit: 1,
//     invoiceFileUrl: "/invoices/invoice1.pdf",
//     confirmBy: "张三",
//     confirmTs: "2024-01-15 10:00:00",
//     sendTs: "2024-01-10 09:00:00"
//   },
//   {
//     id: 2,
//     code: "HT202401002",
//     name: "汽配供应合同",
//     fileUrl: "/files/202511211700183983571.pdf",
//     delivery: 2,
//     deliveryUnit: 2,
//     invoiceFileUrl: "/invoices/invoice2.pdf",
//     confirmBy: "李四",
//     confirmTs: "2024-01-20 12:30:00",
//     sendTs: "2024-01-15 11:30:00"
//   },
//   {
//     id: 3,
//     code: "HT202401003",
//     name: "电子元件采购合同",
//     fileUrl: "/files/202511211700183983571.pdf",
//     delivery: 45,
//     deliveryUnit: 1,
//     invoiceFileUrl: "/invoices/invoice3.pdf",
//     confirmBy: "王五",
//     confirmTs: "2024-02-01 08:45:00",
//     sendTs: "2024-01-25 16:10:00"
//   },
//   {
//     id: 4,
//     code: "HT202401004",
//     name: "机械设备合同",
//     fileUrl: "/files/202511211700183983571.pdf",
//     delivery: 3,
//     deliveryUnit: 2,
//     invoiceFileUrl: "",
//     confirmBy: "赵六",
//     confirmTs: "2024-02-05 14:20:00",
//     sendTs: "2024-01-30 10:00:00"
//   }
// ]

const Page = useMobx(() => {
  const [form] = useForm()
  const { ListStore } = useContext(StoreContext)

  const deliveryRender = useCallback((_: any, item: any) => {
    const delivery = item?.delivery
    const deliveryUnit = item?.deliveryUnit || 1 // 默认天
    if (delivery === undefined || delivery === null) return "-"

    const unitText = deliveryUnitDisplayMap[deliveryUnit] || "天"
    return `${delivery} ${unitText}`
  }, [])

  const titleRender = useCallback(() => {
    return (
      <Row justify="space-between" align="middle">
        <Col> </Col>
        <Col>
          <Space size="middle">
            <Button type="primary" onClick={Zanwu()}>
              导出
            </Button>
          </Space>
        </Col>
      </Row>
    )
  }, [])
  const Zanwu = useCallback((value?: any) => async () => {}, [])

  const onFinish = useCallback(data => {
    const [start, end] = data.range || []
    data.startTime = start ? new Date(start).getTime() : undefined
    data.endTime = end ? new Date(end).getTime() : undefined
    delete data.range
    ListStore.setParams(hetongService.list, data)
  }, [])

  const ConfirmModal = useCallback(
    (val?, item?) => async () => {
      const done = await AsyncModal({
        content: FormModal,
        params: {
          formEle: ConfirmHetong,
          formProps: {
            values: item,
            service: hetongService
          },
          title: "确认合同"
        }
      })
      if (done) {
        ListStore.updateList(hetongService.list)
      }
    },
    []
  )

  const previewContract = useCallback((fileUrl?: string) => {
    if (!fileUrl) {
      Modal.warning({
        title: "提示",
        content: "暂无可预览的合同文件"
      })
      return
    }

    const viewerOrigin = window.location.origin
    const previewBase = `${viewerOrigin}/web/viewer.html?file=`
    const normalizedUrl = functionCommon.requestHost("public") + fileUrl
    const previewUrl = `${previewBase}${encodeURIComponent(normalizedUrl)}`
    window.open(previewUrl, "_blank")
  }, [])

  const renderFileUrl = useCallback(
    (_: string, item: any) => {
      const rawUrl = item?.fileUrl
      if (!rawUrl) return "-"

      const extTarget = rawUrl.split("?")[0]?.toLowerCase() || ""
      const isPdf = extTarget.endsWith(".pdf")

      if (isPdf) {
        return (
          <Button type="link" onClick={() => previewContract(rawUrl)}>
            预览
          </Button>
        )
      }

      const downloadUrl = `${functionCommon.requestHost("public")}${rawUrl}`
      return downloadUrl ? (
        <a href={downloadUrl} target="_blank" rel="noopener noreferrer">
          下载
        </a>
      ) : (
        "-"
      )
    },
    [previewContract]
  )

  const renderInvoiceFileUrl = useCallback(
    (_: string, item: any) => {
      const rawUrl = item?.invoiceFileUrl
      if (!rawUrl) {
        return <span style={{ color: "red" }}>待确认</span>
      }

      const extTarget = rawUrl.split("?")[0]?.toLowerCase() || ""
      const isPdf = extTarget.endsWith(".pdf")

      if (isPdf) {
        return (
          <Button type="link" onClick={() => previewContract(rawUrl)}>
            预览
          </Button>
        )
      }

      const downloadUrl = `${functionCommon.requestHost("public")}${rawUrl}`
      return downloadUrl ? (
        <a href={downloadUrl} target="_blank" rel="noopener noreferrer">
          下载
        </a>
      ) : (
        "-"
      )
    },
    [previewContract]
  )
  return (
    <Row>
      <Col span={24}>
        <FormRender
          form={form}
          onFinish={onFinish}
          layout="inline"
          fieldList={[
            {
              fieldType: "rangeDate",
              formItemConfig: {
                name: "range",
                label: "接收时间"
              },
              config: {
                showTime: !0,
                format: "YYYY-MM-DD HH:mm:ss"
              }
            },
            {
              fieldType: "input",
              formItemConfig: {
                label: "合同编号",
                name: "code"
              },
              config: {
                placeholder: "合同编号"
              }
            },
            {
              fieldType: "input",
              formItemConfig: {
                label: "合同名称",
                name: "name"
              },
              config: {
                placeholder: "合同名称"
              }
            },

            Field_Search
          ]}
        />
      </Col>
      <Col span={24}>
        <ListTable
          title={titleRender}
          apiColumns={[
            IndexRender("id", 80),
            ["code", "合同编号"],
            ["name", "合同名称"],
            ["fileUrl", "合同地址", renderFileUrl],
            ["delivery", "交付期", deliveryRender],
            ["invoiceFileUrl", "开票", renderInvoiceFileUrl],
            ["confirmBy", "确认人"],
            ["confirmTs", "确认时间", DateRender()],
            ["sendTs", "接收时间", DateRender()],
            ["id", "操作", OperateRender([["确认", ConfirmModal]]), { width: 80, fixed: "right" }]
          ]}
          apiService={hetongService.list}
          // testData={hetongTestData}
        />
      </Col>
    </Row>
  )
})

export default Page
